using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.ErrorCode;
using RBAC.Interstructrue;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement.Billing;

namespace RBAC.Write.Api.Application.Handler.ERP.SalesManagement.Billing
{
    /// <summary>
    /// 反审核开票通知单处理器
    /// </summary>
    public class UnAuditBillingNoticeHandler : IRequestHandler<UnAuditBillingNoticeCommand, APIResult<bool>>
    {
        private readonly RBACDbContext _context;
        private readonly ILogger<UnAuditBillingNoticeHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        /// <param name="logger">日志记录器</param>
        public UnAuditBillingNoticeHandler(RBACDbContext context, ILogger<UnAuditBillingNoticeHandler> logger)
        {
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 处理反审核开票通知单请求
        /// </summary>
        /// <param name="request">反审核命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>反审核结果</returns>
        public async Task<APIResult<bool>> Handle(UnAuditBillingNoticeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查找要反审核的开票通知单
                var billingNotice = await _context.BillingAccountings
                    .FirstOrDefaultAsync(b => b.BillNumber == request.BillNumber && !b.IsDeleted, cancellationToken);

                if (billingNotice == null)
                {
                    return new APIResult<bool>
                    {
                        Code = APIEnums.Fail,
                        Msg = "未找到指定的开票通知单"
                    };
                }

                // 检查当前状态是否允许反审核
                if (billingNotice.Status != 1) // 不是审核状态
                {
                    return new APIResult<bool>
                    {
                        Code = APIEnums.Fail,
                        Msg = "只有审核状态的单据才能进行反审核操作"
                    };
                }

                // 更新状态为退回（使用中文状态名：退回）
            billingNotice.Status = 2; // 2=退回
            billingNotice.BillStatus = "退回";
                billingNotice.ReviewDate = null;
                billingNotice.Reviewer = null;

                await _context.SaveChangesAsync(cancellationToken);
                _logger.LogInformation($"开票通知单 {request.BillNumber} 反审核成功，操作员：{request.Operator}");

                return new APIResult<bool>
                {
                    Code = APIEnums.Success,
                    Msg = "开票通知单反审核成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"反审核开票通知单 {request.BillNumber} 失败");
                return new APIResult<bool>
                {
                    Code = APIEnums.Fail,
                    Msg = $"反审核失败：{ex.Message}"
                };
            }
        }


    }
}